package cn.edu.nju.ws.sview.views.data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map.Entry;
import java.util.AbstractMap.SimpleEntry;

import cn.edu.nju.ws.sview.database.DBConnectionFactory;
import cn.edu.nju.ws.sview.views.data.EntityBrowsing.QuadItem;

public class CollectionRelateRecomm extends RelateRecomm{

	public CollectionRelateRecomm(String lang) {
		super(RecType.COLLECTION_RELATION_BASED, lang);
	}

	@Override
	public LinkedList<QuadItem> getRecommandItems(int itemId, int itemType, int requiredNum)
			throws Exception {
		HashMap<Integer, Integer> items = this.getCandidates(itemId);
		String itemIds = "";
		if(items.size() == 0)
			return new LinkedList<QuadItem>();
		for(int id : items.keySet()){
			itemIds += id + ",";
		}
		itemIds = itemIds.substring(0, itemIds.length() - 1);
		LinkedList<QuadItem> ret = new LinkedList<QuadItem>();
		
		//将items中的每个collection的最近访问次数
		HashMap<Integer, Integer> itemTimes = new HashMap<Integer, Integer>();
		try{
			Connection con = DBConnectionFactory.getConnection();
			PreparedStatement ps = con.prepareStatement("SELECT member_id, SUM(times_recent) FROM user_day_visit " +
				"WHERE member_type = 3 AND member_id in (" + itemIds + ") GROUP BY member_id ORDER BY SUM(times_recent) DESC;");
			ResultSet rs = ps.executeQuery();
			while(rs.next()){
				int id = rs.getInt("member_id");
				int times = rs.getInt("SUM(times_recent)");
				itemTimes.put(id, times);
			}
			rs.close();
			ps.close();
			con.close();
		}catch(SQLException e){
			e.printStackTrace();
		}
		
		//找到最近访问次数的最大数字
		Integer maxTimes = 0;
		for(Integer num : itemTimes.values()){
			if(num > maxTimes){
				maxTimes = num;
			}
		}
		
		//得到最近访问次数中最大数字的位数
		String maxT = "" + maxTimes;
		int maxLen = maxT.length();
		
		//将重复次数（items的映射值）乘以maxLen，加上该实体的最近访问次数，得到排序的依据。优先按重复次数排，如果重复次数相同，最近访问越多，排名越靠前
		LinkedList<Entry<Integer, Integer>> toSort = new LinkedList<Entry<Integer, Integer>>(); 
		for(int item : items.keySet()){
			toSort.add(new SimpleEntry<Integer, Integer>(item, (int)(items.get(item) * Math.pow(10.0, 0.0 + maxLen)) + 
					((itemTimes.get(item) == null) ? 0 : itemTimes.get(item))));
		}
		Collections.sort(toSort, new NComparator());
		
		//将拍好顺序的collection包装好返回
		int count = 0;
		for(Entry<Integer, Integer> en : toSort){
			int id = en.getKey();
			ret.add(PackingService.pack(id, this.itemType, this.lang));
			count++;
			if(count == requiredNum)
				break;
		}
		return ret;
	}
	public static void main(String[] args){
		
	}
}
